<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>班次设置基本信息</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${ctx}/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${ctx}/systemStatic/style/admin.css">
    <link rel="stylesheet" href="${ctx}/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="${ctx}/css/public.css">
    <script type="text/javascript">
        var __ctx = "${ctx}";
    </script>
</head>
<body>

<script type="text/html" id="sysWorkTimeSetting">
<form class="layui-form"  requrl="{{ serverPath.basePath }}/system/sysWorkTimeSetting/get"style="padding: 0px 30px;width: 620px;margin-left: auto;margin-right: auto" lay-filter="sysWorkTimeSettingDataForm">

    <div style="margin: 15px 0px;width:620px;height: 471px;overflow: auto;">
        <div class="layui-form-item" style="display:none;">
            <label class="layui-form-label">主键Id</label>
            <div class="layui-input-block">
                <input type="text" name="id"  placeholder="请输入主键Id"
                       autocomplete="off" class="layui-input " maxlength="50" fieldname="id">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">班次名称<span style='color:red'>*</span></label>
            <div class="layui-input-block">
                <input type="text" name="name"  lay-verify="required" placeholder="请输入班次名称"
                       autocomplete="off" class="layui-input " id="settingName" maxlength="33" fieldname="name">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述<span style='color:red'>*</span></label>
            <div class="layui-input-block">
                <input type="text" name="memo"  lay-verify="required" placeholder="请输入描述"
                       autocomplete="off" class="layui-input " id="settingMemo" maxlength="166" fieldname="memo">
            </div>
        </div>

        <button type="button" class="addSubData layui-btn btn-n">增加</button>
        <table style="border: 1px solid #e2e2e2;" lay-filter="subTableData" id="subTableData">
            <tr></tr>
        </table>
    </div>

    <div class="layui-form-item">
        <div style="text-align: center;">
                <a lay-submit lay-filter="sysWorkTimeSetting" class="layui-btn btn-n">提交</a>
            <a id="closeWindow" style="margin-left: 10px;" class="layui-btn btn-n layui-btn-danger btn-save">取消</a>
        </div>
    </div>
</form>
</script>

<div id="view"></div>

<script type="text/html" id="sysWorkTimeStart">
    <input type="text" name="startTime" value="{{d.startTime}}"  placeholder="请输入开始时间" autocomplete="off" class="layui-input dateTimeFiled time-init startTime times" maxlength="50" fieldname="startTime"/>
    </script>
<script type="text/html" id="sysWorkTimeEnd">
    <input type="text" name="endTime" value="{{d.endTime}}"  placeholder="请输入结束时间" autocomplete="off" class="layui-input dateTimeFiled time-init endTime times" maxlength="50" fieldname="endTime"/>
</script>

<!-- 右侧工具栏 -->
<script type="text/html" id="sysWorkTimeRightToolsBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script src="${ctx}/public/component.js" type="text/javascript"></script>
<script src="${ctx}/layui/layui.js"></script>
<script>

    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','common','laydate','jquery','commons','laytpl','table','form','setter'], function () {
        var laydate = layui.laydate;
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var table=layui.table;
        var form = layui.form;
        var setter = layui.setter;
        var commons = layui.commons;

        var gtlHtml = sysWorkTimeSetting.innerHTML;
        var viewHtml = document.getElementById('view');
        var data = {};
        laytpl(gtlHtml).render(data,function (html) {
            viewHtml.innerHTML = html;
        });

        $("#closeWindow").click(function () {
            $(this).attr("href", serverPath.systemPath+setter.sysLinkPath+"sysWorkTimeSetting/view/list");
        });

        var dataBak = [];   // 定义一个空数组,用来存储之前编辑过的数据已经存放新数据
        var sum=0;
        table.render({
            elem: '#subTableData'
            , data: dataBak
            , cols: [[
                {title: '序号', type: 'numbers', Width: 20}
                , {field: 'id', title: '主键',hide:true}
                , {field: 'startTime', title: '开始时间', minWidth: 100,templet: '#sysWorkTimeStart'}
                , {field: 'endTime', title: '结束时间', minWidth: 100,templet: '#sysWorkTimeEnd'}
                , {field: 'memo', title: '描述', minWidth: 100,  edit: 'memo'}
                ,{
                    fixed: 'right',
                    align: 'center',
                    title: '管理',
                    toolbar: '#sysWorkTimeRightToolsBar'
                }
            ]]
            , limit:sum
        })
        $('.addSubData').click(function () {
            sum++;
            dataBak = [];
            dataBak.push({
                "id": ""
                ,"startTime":""
                ,"endTime": ""
                ,"memo": ""
            });

            if (!document.getElementsByClassName) {                   //如果浏览器不支持document.getElementsByClassName
                document.getElementsByClassName = function (className, element) {       //我们先将要写的方法封装成一个函数
                    var children = (element || document).getElementsByTagName('*');     //获取html中所有的DOM节点
                    var elements = [];                                                 //用一个空数组存放要获取的class类名
                    for (var i = 0; i < children.length; i++) {
                        var child = children[i];
                        var classNames = child.className.split(' ');                 //将所有的class节点保存在一个数组之中
                        for (var j = 0; j < classNames.length; j++) {               //遍历循环，将满足要求的class存入elements空数组中
                            if (classNames[j] == className) {
                                elements.push(child);
                                break;
                            }
                        }
                    }
                    return elements;                      //返回新的数组
                };
            }

            var startTimeDocu=document.getElementsByClassName('startTime');
            var endTimeDocu=document.getElementsByClassName('endTime');
            var tableBak = table.cache.subTableData;
            if(tableBak){
                for (var i = 0; i < tableBak.length; i++) {
                    if(startTimeDocu && endTimeDocu){
                        tableBak[i].startTime=startTimeDocu[i];
                        tableBak[i].endTime=endTimeDocu[i];
                    }
                    dataBak.push(tableBak[i]);     //将之前的数组备份
                }
            }
            table.reload("subTableData",{
                data:dataBak,   // 将新数据重新载入表格
                limit:sum
            });
            flashDate();
        });

        flashDate();
        function flashDate() {
            var dateTimeFiledLen = $(".dateTimeFiled");
            for(var i=0;i<dateTimeFiledLen.length;i++){
                laydate.render({
                    elem: dateTimeFiledLen[i] //指定元素
                    ,type: 'time'
                    ,trigger: 'click'
                });
            }
        }

        var id = "${id}";
        $.ajax({
            url:serverPath.basePath + setter.sysLinkPath + "sysWorkTimeSetting/get",
            data:{id:id},
            type:"get",
            contentType: 'application/json',
            dataType: 'json',
            success:function (data) {
                var nowData = data.data;
                if(nowData){
                    dataBak = nowData.sysWorkTimeList;
                    $("#settingName").val(nowData.name);
                    $("#settingMemo").val(nowData.memo);
                    table.reload("subTableData",{
                        data:dataBak,   // 将新数据重新载入表格
                        limit:nowData.sysWorkTimeList.length
                    });
                    sum=nowData.sysWorkTimeList.length;
                    flashDate();
                }
            },error: function(XMLHttpRequest, textStatus, errorThrown) {
                layer.alert("获取数据失败" + XMLHttpRequest.status);
            }
        });


        table.on('tool(subTableData)', function(obj) {
            var data = obj.data, //获得当前行数据
                layEvent = obj.event; //获得 lay-event 对应的值
            switch(layEvent){
                case "del":
                    var $this = $(this);
                    var tr = $this.parents('tr');
                    var trIndex = tr.data('index');
                    layer.confirm('确认删除行吗?', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        //向服务端发送删除指令
                        dataBak.splice(trIndex,1);
                    });
                    break;
            }
        });

        var common = layui.common;
        var index = parent.layer.getFrameIndex(window.name);

        form.on("submit(sysWorkTimeSetting)",function () {
            if (!document.getElementsByClassName) {                   //如果浏览器不支持document.getElementsByClassName
                document.getElementsByClassName = function (className, element) {       //我们先将要写的方法封装成一个函数
                    var children = (element || document).getElementsByTagName('*');     //获取html中所有的DOM节点
                    var elements = [];                                                 //用一个空数组存放要获取的class类名
                    for (var i = 0; i < children.length; i++) {
                        var child = children[i];
                        var classNames = child.className.split(' ');                 //将所有的class节点保存在一个数组之中
                        for (var j = 0; j < classNames.length; j++) {               //遍历循环，将满足要求的class存入elements空数组中
                            if (classNames[j] == className) {
                                elements.push(child);
                                break;
                            }
                        }
                    }
                    return elements;                      //返回新的数组
                };
            }
            var subTableList = layui.table.cache.subTableData;
            var startTimeDocu=document.getElementsByClassName('startTime');
            var endTimeDocu=document.getElementsByClassName('endTime');
            var workTimeData = [];
            for(var i=0;i<startTimeDocu.length;i++){
                var subTableData = {'startTime':startTimeDocu[i].value.toString(),'endTime':endTimeDocu[i].value.toString(),'memo':subTableList[i].memo};
                workTimeData.push(subTableData);
            }
            if(workTimeData.length==0){
				layer.alert('请填写班次时间');
			}else{
				var settingName = $("#settingName").val();
	            var settingMemo = $("#settingMemo").val();
	            var subDataToJson = JSON.stringify(workTimeData);
	            var dataToJson = JSON.stringify({'name':settingName,'memo':settingMemo,'sysWorkTimeList':subDataToJson});
	            if(startTimeDocu[0].value==""){
	            	layer.msg("请填写开始时间");
	            	$('#startTime').focus();
	            }else if(endTimeDocu[0].value==""){
	            	layer.msg("请请填写结束时间");
	            	$('#endTime').focus();
	            }else{
	            	if(parseInt(startTimeDocu[0].value)>parseInt(endTimeDocu[0].value)){
	                	layer.msg("请检查----开始时间不能大于结束时间");
	                	$('#startTime').val("");
	                	$('#endTime').val("");
	                }else{
	                	 $.ajax({
	                         url:serverPath.basePath + setter.sysLinkPath + "sysWorkTimeSetting/save",
	                         data:JSON.stringify({'id':id,'name':settingName,'memo':settingMemo,'sysWorkTimeList':workTimeData}),
	                         type:"post",
	                         contentType: 'application/json',
	                         dataType: 'json',
	                         success : function (data) {
	                             if(commons._filterRecord(data)){
	                                 layer.alert(data.msg,function () {
	                                     location.href = serverPath.systemPath+setter.sysLinkPath+'sysWorkTimeSetting/view/list' ;
	                                     layer.close(index);
	                                 });
	                             }else{
	                                 layer.msg(data.msg);
	                             }
	                             return false;
	                         },
	                         error : function (XMLHttpRequest, textStatus, errorThrown) {
	                             layer.alert("保存失败！" + XMLHttpRequest.status);
	                         }
	                     })
	                }
	            }
			}
        })
    });
</script>
</body>
</html>